package com.wdd.myplatform.utils;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Base64文件工具类
 * @author Administrator
 */
public class Base64FileUtils {

    /**
     * 解析报文
     * @param path 传递的路径
     * @return
     */
    public static String analyzeMessage(String path){
        String fileName  = path;
        StringBuilder result = new StringBuilder();
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(fileName));
            String s= null;
            while((s=br.readLine()) != null){
                result.append(s);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result.toString());
        return result.toString();
    }

    /**
     * 文件上传
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[0]);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64DecodedMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * base64转图片
     * @param imgStr
     * @param path
     * @return
     */
    public static boolean base64StrToImage(String imgStr, String path) {
            if (imgStr == null){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //文件夹不存在则自动创建
            File tempFile = new File(path);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(tempFile);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 根据文件下载url转为base64
     * @param imgUrl
     * @return
     */
    public static String getBase64ByImgUrl(String imgUrl){
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try{
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return encode(outStream.toByteArray());
        }catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            if(is != null)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outStream != null)
            {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpUrl != null)
            {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }

    public static String url2Base64Img(String url){
        try{
            URL uploadUrl = new URL(url);
            HttpURLConnection httpUrl = (HttpURLConnection) uploadUrl.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            InputStream is = httpUrl.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            while( (len=is.read(buffer)) != -1 ){
                outStream.write(buffer, 0, len);
            }
            //对字节数组Base64编码
            BASE64Encoder decoder = new BASE64Encoder();
            return decoder.encode(outStream.toByteArray());
        } catch (Exception ex){
            return "";
        }
    }

    /**
     * base64 编码转换为 BufferedImage
     * @param base64
     * @return
     */
    public  static BufferedImage base64ToBufferedImage(String base64) {
        Base64.Decoder decoder = Base64.getDecoder();
//        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        try {
            byte[] bytes1 = decoder.decode(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            return ImageIO.read(bais);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * file转BufferedImage
     * @param file
     * @return
     */
    public static BufferedImage InputImage(MultipartFile file) {
        BufferedImage srcImage = null;
        try {
            FileInputStream in = (FileInputStream) file.getInputStream();
            srcImage = ImageIO.read(in);
        } catch (IOException e) {
            System.out.println("读取图片文件出错！" + e.getMessage());
        }
        return srcImage;
    }

     /**
       * 字符串转图片
       * @param base64Str
       * @return
       */
     public static byte[] decode(String base64Str){
           byte[] b = null;
           BASE64Decoder decoder = new BASE64Decoder();
           try {
                     b = decoder.decodeBuffer(replaceEnter(base64Str));
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             return b;
     }

        /**
       * 图片转字符串
       * @param image
       * @return
       */
     public static String encode(byte[] image){
           BASE64Encoder decoder = new BASE64Encoder();
           return replaceEnter(decoder.encode(image));
     }

    public String encode(String uri){
           BASE64Encoder encoder = new BASE64Encoder();
           return replaceEnter(encoder.encode(uri.getBytes()));
       }

    private static String replaceEnter(String str){
                     String reg ="[\n-\r]";
                     Pattern p = Pattern.compile(reg);
                     Matcher m = p.matcher(str);
                     return m.replaceAll("");
        }


    public static void main(String[] args) throws Exception {
        String base64ByImgUrl = getBase64ByImgUrl("http://192.168.103.202:8811/group1/M00/00/02/wKhnymF6FZ2ACYSbAAAvs_JJAhY541.PNG");
        String base64ByImgUrl1 = url2Base64Img("http://192.168.103.202:8811/group1/M00/00/02/wKhnymF6FZ2ACYSbAAAvs_JJAhY541.PNG");

    }
}
